<template>
  <view>
    <el-divider content-position="left">
      <span class="h1">文章管理</span>
    </el-divider>
    <h1>文章编辑</h1>
    <br>
    <div>
      <el-button type="primary" :dark="isDark" plain @click="addData">+ 新增</el-button>
      <el-button type="danger" :dark="isDark" plain @click="batchDel">- 批量删除</el-button>
    </div>
    <br>
    <div>
      <!-- 分类选择器 -->
      <el-select v-model="query.categoryId" placeholder="请选择分类" style="width: 200px">
        <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.categoryName"
          :value="item.categoryId" />
      </el-select>

      <el-input v-model="query.title" placeholder="title" style="width: 200px"></el-input>
      <el-button type="primary" :dark="isDark" plain @click="search">查询</el-button>
      <el-button type="primary" :dark="isDark" plain @click="reset">重置</el-button>
    </div>
    <br>
    <!-- element-plus表格 -->
    <el-table ref="tableRef" :data="formData" style="width: 100%" @selection-change="handleSelectionChange">

      <el-table-column type="expand">
        <template #default="scope">
          <h1 style="font-size: 25px;padding:5px 40px">{{ scope.row.title }}</h1>
          <VMdTextareaEditor style="padding:5px 40px" v-model="scope.row.content" :mode="`preview`"/>
          <!-- <div style="padding:5px 40px" v-html="scope.row.content"></div> -->
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="categoryName" label="类别" />
      <el-table-column show-overflow-tooltip="true" prop="content" label="内容" width="160" />
      <el-table-column show-overflow-tooltip="true" prop="summary" label="摘要" />
      <el-table-column prop="image" label="封面">
        <template #default="scope">
          <el-image :src="scope.row.image" />
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="发布时间" />
      <el-table-column prop="views" label="阅览量" />
      <el-table-column label="状态">
        <template #default="scope">
          <span v-if="scope.row.status == 1">审核中</span>
          <span v-else-if="scope.row.status == 2">发表</span>
          <span v-else-if="scope.row.status == 0">草稿</span>
          <span v-else-if="scope.row.status == -1">审核不通过</span>
        </template>
      </el-table-column>
      <el-table-column prop="tagList" label="标签">
        <template #default="scope">
          <el-tag v-for="(item, index) in scope.row.tagList" :key="index">{{ item.tagName }}</el-tag>
        </template>

      </el-table-column>

      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="edit(row)">编辑
          </el-button>
          <el-popconfirm title="确定要删除吗?" @confirm="delData(row)" confirm-button-text="是" cancel-button-text="否">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <br>

    <!-- element-plus分页 -->
    <el-pagination v-model:currentPage="query.current" :page-size="pageSize" layout="total,  prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 新增/编辑表单 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
      <el-form :model="formDTO" ref="vForm" :rules="rules" label-position="right" label-width="80px" size="medium"
        @submit.prevent>
        <el-form-item label="ID" prop="postId">
          <el-input v-model="formDTO.postId" type="text" clearable :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="formDTO.categoryId" placeholder="请选择分类" style="width: 200px">
            <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.categoryName"
              :value="item.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="formDTO.title" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tagList" class="label-center-align">
          <div class="flex gap-2">
            <el-tag v-for="tag in formDTO.tagName" :key="tag" closable :disable-transitions="false"
              @close="handleClose(tag)">
              {{ tag }}
            </el-tag>
            <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
              @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
            <el-button v-else class="button-new-tag" size="small" @click="showInput">
              + New Tag
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="内容" prop="content">
        <VMdTextareaEditor v-model="formDTO.content" :mode="mode" height="700px"
		  	left-toolbar="true" @changeMode="handleModeChange" />
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input v-model="formDTO.summary" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="image" class="label-center-align">
          <el-upload :file-list="imageFileList" :headers="imageUploadHeaders" :data="imageUploadData"
            :on-success="uploadSuccess" list-type="picture-card" show-file-list :limit="1"
            :action="url"> 
            <!-- "'http://'+import.meta.env.VITE_APP_ADRESS+':'+import.meta.env.VITE_APP_PORT+'/admin/common/upload'" -->
            <template #default><i
                class="el-icon-plus"></i></template></el-upload>
        </el-form-item>
        <!-- <el-form-item label="封面" prop="image">
          <el-input v-model="formDTO.image" type="text" clearable></el-input>
          <img :src="formDTO.image" style="width: 100px; height: 100px;">
        </el-form-item> -->
        <!-- <el-form-item label="浏览量" prop="views">
          <el-input v-model="formDTO.views" type="text" clearable></el-input>
        </el-form-item> -->
        <el-form-item label="状态" prop="status" class="label-right-align">
          <el-select v-model="formDTO.status">
            <el-option label="发表" :value="2"></el-option>
            <el-option label="审核中" :value="1"></el-option>
            <el-option label="草稿" :value="0"></el-option>
            <el-option label="审核未通过" :value="-1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </view>
</template>

<script setup>
import { ref, reactive, setDevtoolsHook, onMounted, nextTick } from "vue";
import { post, category } from '@/api'
import { useRoute, useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import VMdTextareaEditor from "@kangc/v-md-editor";
const router = useRouter()
//分页数据
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const list = ref([]);
//删除列表
const delList = ref([]);
const tableRef = ref();
//弹出层
const dialogVisible = ref(false);
const dialogTitle = ref("");
const vForm = ref(null);
//分类列表
const categoryList = ref([])
//封面图片上传参数
const url = 'http://'+import.meta.env.VITE_APP_ADRESS+':'+import.meta.env.VITE_APP_PORT+'/admin/common/upload'
const imageFileList = ref([])
const imageUploadHeaders = ref({
	token: sessionStorage.getItem("token")
})
const imageUploadData = ref({})
const uploadSuccess = (res, file) => {
	console.log(res)
	// 'res' 是上传成功的响应数据，'file' 是文件对象
	// 假设服务器返回的响应数据中包含图片URL
	if (res.code === 200) { // 根据你的后端实际响应格式来处理

		const imageUrl = res.data; // 假设图片URL在res.data.url中
		console.log("图片上传成功，URL:", imageUrl);

		// 将图片URL添加到formData中或其他需要的地方
		formDTO.value.image = imageUrl;
	}
};

//表单数据
const formData = ref([]);

//验证规则
const rules = ref({
  postId: [
    {
      pattern: /^[-]?\d+(\.\d+)?$/,
      trigger: ["blur", "change"],
      message: "",
    },
  ],
  categoryId: [
    {
      required: true,
      message: "字段值不可为空",
    },
  ],
  title: [
    {
      required: true,
      message: "字段值不可为空",
    },
  ],
  content: [
    {
      required: true,
      message: "字段值不可为空",
    },
  ],
  summary: [
    {
      required: true,
      message: "字段值不可为空",
    },
  ],
  status: [
    {
      required: true,
      message: "字段值不可为空",
    },
  ],
});

//提交表单结构
const formDTO = ref({
  postId: "",
  categoryId: "",
  title: "",
  content: "",
  summary: "",
  image: "",
  views: "",
  status: "",
  tagName: [], // 修改属性名
});

//查询参数
const query = ref({
  pageSize: 10,
  current: 1,
  categoryId: "",
  title: "",
});


/**
 * 数据处理-------------------------
 */

/**
 * 编辑
 */
const edit = (row) => {
  dialogTitle.value = "编辑表单";
  dialogVisible.value = true;
  if (vForm.value) {
    vForm.value.resetFields();
  }
  // 使用新属性名tagName，并转换tagList
  formDTO.value.tagName = row.tagList.map(tag => tag.tagName);
  // 复制其他属性
  Object.assign(formDTO.value, row, { tagName: formDTO.value.tagName });
};

/**
 * 删除
 */
const delData = (row) => {
  del([row.postId])
  console.log(row.postId);
};

/**
 * 批量删除
 */
const batchDel = () => {
  del(delList.value);
  console.log(delList.value);
  // 清空选中列表
  tableRef.value.clearSelection();
};

/**
 * 查询
 */
const search = () => {
  get()
  console.log(query.value);
};

/**
 * 重置
 */
const reset = () => {
  query.value = {
    pageSize: 10,
    current: 1,
    categoryId: "",
    title: "",
  };
  get()
};

/**
 * 新增
 */
const addData = () => {
  router.push("/home/addpost")
  // dialogTitle.value = "新增表单";
  // dialogVisible.value = true;
  // formDTO.value = {};
  // // 重置表单验证状态
  // if (vForm.value) {
  //   vForm.value.resetFields();
  // }
};

/**
 * 提交
 */
const submit = () => {
  if (vForm.value) {
    vForm.value.validate((valid) => {
      if (valid) {
        // 使用新属性名tagName进行提交
        if (dialogTitle.value === '编辑表单') {
          put(formDTO.value);
        } else {
          add(formDTO.value);
        }
        dialogVisible.value = false;
      } else {
        console.error('表单验证失败');
      }
    });
  }
};

/**
 * 监听分页
 */
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
  console.log(formDTO.value);
};

/**
 * 选择
 */
const handleSelectionChange = (val) => {
  //筛出id列表
  delList.value = val.map((item) => item.postId);
  console.log(val);
};

const handleCurrentChange = (val) => {
  console.log(val);
  get()
}

/**
 * 添加标签
 */
const InputRef = ref()
const inputValue = ref('')
const inputVisible = ref(false)

// 编辑标签的方法
const handleClose = (tagName) => {
  const index = formDTO.value.tagName.indexOf(tagName);
  if (index > -1) {
    formDTO.value.tagName.splice(index, 1);
  }
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    if (InputRef.value && InputRef.value.input) {
      InputRef.value.input.focus();
    }
  });
};

const handleInputConfirm = () => {
  if (inputValue.value && !formDTO.value.tagName.includes(inputValue.value)) {
    formDTO.value.tagName.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = '';
};


/**
 * 接口调用------------------------------------------------------------
 */

onMounted(() => {
  get()
  getCategory()
})

const add = (data) => {
  console.log("添加数据:", data)
  get()
}

const del = (data) => {
  post.del(data)
    .then(res => {
      ElNotification({
        title: 'Success',
        message: '删除成功',
        type: 'success',
      })
      console.log(res);
      get()
    }).catch(err => {
      ElNotification({
        title: 'Error',
        message: '删除失败',
        type: 'error',
      })
    })
  console.log("删除数据:", data)

}

const get = (data = query.value) => {
  post.get(data).then((res) => {
    formData.value = res.data.data.records
    total.value = res.data.data.total
    console.log("获取数据:", res.data)
  })

}

const put = (data) => {
  console.log("要修改的数据:", data);
  post.put(data)
    .then(res => {
      ElNotification({
        title: 'Success',
        message: '编辑成功',
        type: 'success',
      })
      get()
    }).catch(err => {
      ElNotification({
        title: 'Error',
        message: '编辑失败',
        type: 'error',
      })
    })

}

const getCategory = () => {
  category.get().then((res) => {
    categoryList.value = res.data.data
    console.log("获取分类:", res.data)
  })
}

</script>

<style scoped>
.h1 {
  font-size: 25px;
}
</style>